<template>
  <div class="flow-up-h5">
    <!-- 头部操作区 -->
    <div class="header-section">
      <div class="add-follow-btn" v-if="!followUpValue" @click="addFollow">
        <div class="avatar">
          <el-image class="w-100% h-100%" :src="avatar"></el-image>
        </div>
        <div class="input-placeholder">写跟进...</div>
        <el-icon class="add-icon"><Edit /></el-icon>
      </div>
    </div>

    <!-- 添加跟进表单 -->
    <div class="create-follow-section" v-if="followUpValue">
      <div class="form-header">
        <div class="avatar">
          <el-image class="w-100% h-100%" :src="avatar"></el-image>
        </div>
        <span class="form-title">添加跟进记录</span>
      </div>

      <el-form
        ref="formRef"
        v-loading="formLoading"
        :model="formData"
        :rules="formRules"
        label-position="top"
        class="mobile-form"
      >
        <el-form-item label="跟进类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择跟进类型" class="w-100%">
            <el-option
              v-for="dict in followOptionsList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="下次联系时间" prop="nextTime">
          <el-date-picker
            v-model="formData.nextTime"
            placeholder="选择下次联系时间"
            type="date"
            value-format="x"
            class="w-100%"
          />
        </el-form-item>

        <el-form-item label="跟进内容" prop="content">
          <el-input
            v-model="formData.content"
            :rows="4"
            type="textarea"
            placeholder="请输入跟进内容"
            class="w-100%"
          />
        </el-form-item>

        <el-form-item label="图片" prop="picUrls">
          <UploadImgs v-model="formData.picUrls" width="80px" height="80px" />
        </el-form-item>

        <el-form-item label="附件" prop="fileUrls">
          <UploadFile v-model="formData.fileUrls" class="w-100%" />
        </el-form-item>

        <el-form-item
          label="关联联系人"
          prop="contactIds"
          v-if="formData.bizType == BizTypeEnum.CRM_CUSTOMER"
        >
          <el-button @click="handleOpenContact" class="w-100%" plain>
            <Icon class="mr-5px" icon="ep:plus" />
            添加联系人
          </el-button>
          <FollowUpRecordContactForm :contacts="formData.contacts" />
        </el-form-item>

        <el-form-item
          label="关联商机"
          prop="businessIds"
          v-if="formData.bizType == BizTypeEnum.CRM_CUSTOMER"
        >
          <el-button @click="handleOpenBusiness" class="w-100%" plain>
            <Icon class="mr-5px" icon="ep:plus" />
            添加商机
          </el-button>
          <FollowUpRecordBusinessForm :businesses="formData.businesses" />
        </el-form-item>
      </el-form>

      <div class="form-actions">
        <el-button type="primary" @click="submitForm" :loading="formLoading" class="submit-btn">
          发布
        </el-button>
        <el-button @click="followUpValue = false" class="cancel-btn"> 取消 </el-button>
      </div>
    </div>

    <!-- 筛选和统计区 -->
    <div class="filter-section" v-if="!followUpValue">
      <div class="stats">
        <span class="record-count">跟进记录 ({{ total }})</span>
      </div>
      <div class="filter-btn" @click="showFilter = true">
        <el-icon><Filter /></el-icon>
        <span>筛选</span>
      </div>
    </div>

    <!-- 跟进记录列表 -->
    <div class="records-list" v-if="!followUpValue">
      <div v-for="activity in processedList" :key="activity.id" class="record-item">
        <!-- 日期分组 -->
        <div v-if="activity.isShow" class="date-divider">
          <div class="date-info">
            <div class="day">{{ getDay(activity.createTime) }}</div>
            <div class="month-year">
              {{ getYear(activity.createTime) }}.{{ getMonth(activity.createTime) }}
            </div>
          </div>
        </div>

        <!-- 记录内容 -->
        <div class="record-content">
          <div class="record-header">
            <div class="creator-info">
              <span class="creator-name">{{ activity.creatorName }}</span>
              <el-tag size="small" class="record-type-tag"> {{ crmType[bizType] }}跟进记录 </el-tag>
            </div>
            <div class="record-time">
              {{ formatDate(activity.createTime, 'HH:mm') }}
            </div>
          </div>

          <div class="record-body">
            <div class="content-text">{{ activity.content }}</div>

            <!-- 跟进类型和状态 -->
            <div class="record-meta">
              <el-tag v-if="activity.type == 0" type="info" size="small"> 系统外呼 </el-tag>
              <el-tag v-else-if="activity.typeName" type="primary" size="small">
                {{ activity.typeName }}
              </el-tag>
              <el-tag v-if="activity.type == 1 && !activity.callStatus" type="warning" size="small">
                未接通
              </el-tag>
            </div>

            <!-- 语音记录 -->
            <div v-if="activity.callLogId && activity.callRecordUrl" class="audio-section">
              <AudioPlayers :url="activity.callRecordUrl" />
              <el-button size="small" text @click="showDiag(activity)" class="voice-to-text-btn">
                <el-icon><ChatDotRound /></el-icon>
                语音转文字
              </el-button>
            </div>

            <!-- 图片附件 -->
            <div v-if="activity.picUrls && activity.picUrls.length" class="images-section">
              <el-image
                v-for="(url, index) in activity.picUrls"
                :key="'img' + index"
                :src="url"
                :preview-src-list="activity.picUrls"
                :initial-index="index"
                class="preview-image"
                fit="cover"
              />
            </div>

            <!-- 文件附件 -->
            <div v-if="activity.fileUrls && activity.fileUrls.length" class="files-section">
              <div
                v-for="(url, index) in activity.fileUrls"
                :key="'file' + index"
                class="file-item"
              >
                <el-icon><Document /></el-icon>
                <span>附件{{ index + 1 }}</span>
                <el-link :href="url" :icon="Download" class="download-link"></el-link>
              </div>
            </div>

            <!-- 关联信息 -->
            <div class="related-info">
              <div
                v-if="bizType === BizTypeEnum.CRM_CUSTOMER && activity.contacts.length"
                class="related-contacts"
              >
                <span class="label">关联联系人：</span>
                <el-link
                  v-for="contact in activity.contacts"
                  :key="'contact-' + contact.id"
                  type="primary"
                  @click="openContactDetail(contact.id)"
                  class="related-link"
                >
                  {{ contact.name }}
                </el-link>
              </div>

              <div v-if="activity.businesses.length" class="related-businesses">
                <span class="label">关联商机：</span>
                <el-link
                  v-for="business in activity.businesses"
                  :key="'business-' + business.id"
                  type="primary"
                  @click="openBusinessDetail(business.id)"
                  class="related-link"
                >
                  {{ business.name }}
                </el-link>
              </div>

              <div v-if="activity.nextTime" class="next-time">
                <span class="label">下次联系时间：</span>
                <span>{{ formatDate(activity.nextTime) }}</span>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="record-actions">
            <el-button size="small" text @click="copyContent(activity.content)" class="action-btn">
              <el-icon><CopyDocument /></el-icon>
            </el-button>
            <el-button
              size="small"
              text
              @click="delFlow(activity.id)"
              class="action-btn delete-btn"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div class="load-more" v-if="!isMore" @click="pageNext">
        <el-button :loading="loading" text>
          <el-icon><ArrowDown /></el-icon>
          加载更多
        </el-button>
      </div>

      <div class="no-more" v-else-if="list.length > 0"> 没有更多数据了 </div>

      <div class="empty-state" v-if="list.length === 0 && !loading">
        <el-empty description="暂无跟进记录" />
      </div>
    </div>

    <!-- 筛选弹窗 -->
    <el-drawer v-model="showFilter" title="筛选条件" direction="btt" size="300px">
      <div class="filter-content">
        <el-form label-position="top">
          <el-form-item label="跟进类型">
            <el-select v-model="queryParams.type" placeholder="请选择" class="w-100%">
              <el-option
                v-for="item in followupOption"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <div class="filter-actions">
          <el-button @click="resetFilter" class="w-100%" plain> 重置 </el-button>
          <el-button type="primary" @click="applyFilter" class="w-100%"> 确定 </el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 弹窗组件 -->
    <ContactListModal
      ref="contactTableSelectRef"
      :customer-id="formData.bizId"
      @success="handleAddContact"
      :is-width="true"
    />
    <BusinessListModal
      ref="businessTableSelectRef"
      :customer-id="formData.bizId"
      @success="handleAddBusiness"
      :is-width="true"
    />
    <DetailDes ref="detailRef" />
  </div>
</template>

<script setup lang="ts">
import {
  Edit,
  Filter,
  CopyDocument,
  Delete,
  ArrowDown,
  ChatDotRound,
  Document,
  Download
} from '@element-plus/icons-vue'
import avatarImg from '@/assets/imgs/avatar.gif'
import { FollowUpRecordApi, FollowUpRecordVO } from '@/api/crm/followup'
import { BizTypeEnum } from '@/api/crm/permission'
import FollowUpRecordBusinessForm from '@/views/crm/followup/components/FollowUpRecordBusinessForm.vue'
import FollowUpRecordContactForm from '@/views/crm/followup/components/FollowUpRecordContactForm.vue'
import BusinessListModal from '@/views/crm/business/components/BusinessListModal.vue'
import * as BusinessApi from '@/api/crm/business'
import ContactListModal from '@/views/crm/contact/components/ContactListModal.vue'
import * as ContactApi from '@/api/crm/contact'
import { getFollowTypeConfigList } from '@/api/crm/module/index'
import router from '@/router'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { formatDate } from '@/utils/public'
import DetailDes from '@/views/call/record/detail.vue'

defineOptions({ name: 'FollowUpRecordH5' })

const crmType = {
  1: '线索',
  2: '客户',
  3: '联系人',
  4: '商机',
  5: '合同',
  6: '产品',
  7: '回款',
  8: '回款计划'
}

const { wsCache } = useCache()
const user = wsCache.get(CACHE_KEY.USER)
const avatar = user.user.avatar ? user.user.avatar : avatarImg

const props = defineProps({
  clueValue: Object,
  bizType: String
})

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  bizType: '',
  bizId: '',
  type: ''
})

const { t } = useI18n()
const message = useMessage()
const followUpValue = ref(false)
const showFilter = ref(false)
const formLoading = ref(false)
const loading = ref(false)
const list = ref([])
const total = ref(0)

const formData = ref({
  bizType: undefined,
  bizId: -1,
  bizIdList: [],
  businesses: [],
  contacts: [],
  moduleId: undefined
})

const followupOption = ref([
  { name: '全部', id: '' },
  { name: '系统外呼', id: '0' }
])

const formRules = reactive({
  type: [{ required: true, message: '跟进类型不能为空', trigger: 'change' }],
  content: [{ required: true, message: '跟进内容不能为空', trigger: 'blur' }],
  nextTime: [{ required: true, message: '下次联系时间不能为空', trigger: 'blur' }]
})

// 日期处理函数
const getYear = (timestamp) => new Date(timestamp).getFullYear()
const getMonth = (timestamp) => String(new Date(timestamp).getMonth() + 1).padStart(2, '0')
const getDay = (timestamp) => String(new Date(timestamp).getDate()).padStart(2, '0')

// 处理列表数据，添加日期分组
const processedList = computed(() => {
  return list.value.map((item, index, arr) => {
    const currentDate = formatDate(item.createTime, 'YYYY-MM-DD')
    const prevDate = index > 0 ? formatDate(arr[index - 1].createTime, 'YYYY-MM-DD') : null
    return {
      ...item,
      isShow: currentDate !== prevDate
    }
  })
})

const isMore = computed(() => {
  return list.value.length >= total.value
})

const formRef = ref()
const followOptionsList = ref([])
const detailRef = ref(null)
const contactTableSelectRef = ref()
const businessTableSelectRef = ref()

// 获取跟进记录列表
const getList = async () => {
  loading.value = true
  try {
    const data = await FollowUpRecordApi.getFollowUpRecordPage(queryParams)
    if (queryParams.pageNo === 1) {
      list.value = data.list
    } else {
      list.value.push(...data.list)
    }
    total.value = data.total
  } finally {
    loading.value = false
  }
}

// 加载更多
const pageNext = async () => {
  queryParams.pageNo += 1
  await getList()
}

// 获取跟进类型列表
const getFollowList = async () => {
  const data = await getFollowTypeConfigList({ moduleId: formData.value.moduleId })
  followOptionsList.value = data
  followupOption.value = [...followupOption.value, ...data]
}

// 添加跟进
const addFollow = () => {
  formData.value.businesses = []
  formData.value.contacts = []
  formData.value.bizIdList = []
  formData.value.type = ''
  formData.value.nextTime = ''
  formData.value.content = ''
  followUpValue.value = true
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = {
      ...formData.value,
      contactIds: formData.value.contacts.map((item) => item.id),
      businessIds: formData.value.businesses.map((item) => item.id)
    }
    await FollowUpRecordApi.createFollowUpRecord(data)
    message.success(t('common.createSuccess'))
    followUpValue.value = false
    queryParams.pageNo = 1
    getList()
  } finally {
    formLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  formData.value.businesses = []
  formData.value.contacts = []
  formData.value.bizIdList = []
}

// 筛选相关
const applyFilter = () => {
  queryParams.pageNo = 1
  getList()
  showFilter.value = false
}

const resetFilter = () => {
  queryParams.type = ''
  queryParams.pageNo = 1
  getList()
  showFilter.value = false
}

// 关联联系人
const handleOpenContact = () => {
  contactTableSelectRef.value?.open()
}

const handleAddContact = (contactId: [], newContacts: ContactApi.ContactVO[]) => {
  newContacts.forEach((contact) => {
    if (!formData.value.contacts.some((item) => item.id === contact.id)) {
      formData.value.contacts.push(contact)
    }
  })
}

// 关联商机
const handleOpenBusiness = () => {
  businessTableSelectRef.value?.open()
}

const handleAddBusiness = (businessId, newBusinesses: BusinessApi.BusinessVO[]) => {
  newBusinesses.forEach((business) => {
    if (!formData.value.businesses.some((item) => item.id === business.id)) {
      formData.value.businesses.push(business)
    }
  })
}

// 打开详情页面
const openContactDetail = (id: number) => {
  router.push({ name: 'CrmContactDetail', params: { id } })
}

const openBusinessDetail = (id: number) => {
  router.push({ name: 'CrmBusinessDetail', params: { id } })
}

// 语音转文字
const showDiag = (item) => {
  detailRef.value.open(item.callLogId)
}

// 复制内容
const copyContent = (txt) => {
  navigator.clipboard
    .writeText(txt)
    .then(() => {
      ElMessage.success('复制成功')
    })
    .catch((err) => {
      ElMessage.error('无法复制文本: ' + err)
    })
}

// 删除跟进记录
const delFlow = (id) => {
  ElMessageBox.confirm('确定要删除当前数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const data = await FollowUpRecordApi.deleteFollowUpRecord(id)
      if (data) ElMessage.success('删除成功!')
      queryParams.pageNo = 1
      getList()
    })
    .catch(() => {})
}

// 监听props变化
watch(
  () => [props.clueValue, props.bizType],
  ([val, val2]) => {
    if (Object.keys(val || {}).length && val2) {
      resetForm()
      formData.value.bizId = val.id
      formData.value.moduleId = val.moduleId
      formData.value.bizType = val2
      queryParams.pageNo = 1
      queryParams.bizType = val2
      queryParams.bizId = val.id
      getList()
      getFollowList()
    }
  },
  { deep: true, immediate: true }
)
</script>

<style lang="scss" scoped>
.flow-up-h5 {
  background-color: #f5f5f5;

  .header-section {
    padding: 16px;
    background: #fff;
    border-bottom: 1px solid #eee;

    .add-follow-btn {
      display: flex;
      align-items: center;
      padding: 12px 16px;
      background: #f8f9fa;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s;

      &:active {
        background: #e9ecef;
      }

      .avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        margin-right: 12px;
        overflow: hidden;
      }

      .input-placeholder {
        flex: 1;
        color: #999;
        font-size: 14px;
      }

      .add-icon {
        color: #409eff;
        font-size: 18px;
      }
    }
  }

  .create-follow-section {
    background: #fff;

    .form-header {
      display: flex;
      align-items: center;
      padding: 16px;
      border-bottom: 1px solid #eee;

      .avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        margin-right: 12px;
        overflow: hidden;
      }

      .form-title {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
    }

    .mobile-form {
      padding: 16px;

      :deep(.el-form-item) {
        margin-bottom: 20px;

        .el-form-item__label {
          font-size: 14px;
          font-weight: 500;
          color: #333;
          margin-bottom: 8px;
        }
      }

      :deep(.el-input__wrapper) {
        border-radius: 6px;
      }

      :deep(.el-select) {
        width: 100%;
      }
    }

    .form-actions {
      padding: 16px;
      display: flex;
      gap: 12px;

      .submit-btn {
        flex: 2;
        height: 44px;
        border-radius: 6px;
        font-size: 16px;
      }

      .cancel-btn {
        flex: 1;
        height: 44px;
        border-radius: 6px;
        font-size: 16px;
      }
    }
  }

  .filter-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background: #fff;
    border-bottom: 1px solid #eee;

    .stats {
      .record-count {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
    }

    .filter-btn {
      display: flex;
      align-items: center;
      gap: 4px;
      color: #666;
      font-size: 14px;
      cursor: pointer;

      &:active {
        color: #409eff;
      }
    }
  }

  .records-list {
    .record-item {
      margin-bottom: 8px;

      .date-divider {
        display: flex;
        align-items: center;
        padding: 12px 16px;

        .date-info {
          display: flex;
          flex-direction: column;
          align-items: center;
          width: 60px;

          .day {
            font-size: 20px;
            font-weight: bold;
            color: #333;
            line-height: 1;
          }

          .month-year {
            font-size: 12px;
            color: #666;
            margin-top: 2px;
          }
        }
      }

      .record-content {
        background: #fff;
        margin: 0 16px;
        border-radius: 8px;
        padding: 16px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

        .record-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 12px;

          .creator-info {
            display: flex;
            flex-direction: column;
            gap: 6px;

            .creator-name {
              font-size: 14px;
              font-weight: 500;
              color: #333;
            }

            .record-type-tag {
              align-self: flex-start;
            }
          }

          .record-time {
            font-size: 12px;
            color: #999;
          }
        }

        .record-body {
          .content-text {
            font-size: 14px;
            color: #333;
            line-height: 1.5;
            margin-bottom: 12px;
          }

          .record-meta {
            display: flex;
            gap: 8px;
            margin-bottom: 12px;
          }

          .audio-section {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px;
            background: #f8f9fa;
            border-radius: 6px;
            margin-bottom: 12px;

            .voice-to-text-btn {
              font-size: 12px;
            }
          }

          .images-section {
            display: flex;
            gap: 8px;
            margin-bottom: 12px;
            flex-wrap: wrap;

            .preview-image {
              width: 60px;
              height: 60px;
              border-radius: 4px;
              cursor: pointer;
            }
          }

          .files-section {
            margin-bottom: 12px;

            .file-item {
              display: flex;
              align-items: center;
              gap: 8px;
              padding: 8px 12px;
              background: #f8f9fa;
              border-radius: 4px;
              margin-bottom: 4px;

              span {
                flex: 1;
                font-size: 14px;
                color: #333;
              }

              .download-link {
                font-size: 12px;
              }
            }
          }

          .related-info {
            font-size: 12px;
            color: #666;

            .related-contacts,
            .related-businesses,
            .next-time {
              margin-bottom: 4px;

              .label {
                margin-right: 4px;
              }

              .related-link {
                margin-right: 8px;
                font-size: 12px;
              }
            }
          }
        }

        .record-actions {
          display: flex;
          justify-content: flex-end;
          gap: 8px;
          margin-top: 12px;
          padding-top: 12px;
          border-top: 1px solid #eee;

          .action-btn {
            padding: 4px 8px;

            &.delete-btn {
              color: #f56c6c;

              &:hover {
                background: #fef0f0;
              }
            }
          }
        }
      }
    }

    .load-more {
      text-align: center;
      padding: 20px;
    }

    .no-more {
      text-align: center;
      padding: 20px;
      color: #999;
      font-size: 14px;
    }

    .empty-state {
      padding: 60px 20px;
    }
  }

  .filter-content {
    padding: 20px;

    .filter-actions {
      display: flex;
      gap: 12px;
      margin-top: 24px;
    }
  }
}

// 移动端适配
@media (max-width: 768px) {
  .flow-up-h5 {
    .create-follow-section {
      .mobile-form {
        :deep(.el-form-item) {
          .el-form-item__label {
            font-size: 13px;
          }
        }

        :deep(.el-input) {
          font-size: 16px; // 防止iOS缩放
        }

        :deep(.el-textarea__inner) {
          font-size: 16px; // 防止iOS缩放
        }
      }
    }

    .records-list {
      .record-item {
        .record-content {
          padding: 12px;
        }
      }
    }
  }
}
</style>
